package com.tc.classloader;

import java.net.URL;
import java.net.URLClassLoader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by cai.tian on 2018/1/10.
 */
public class BaseClassLoader extends URLClassLoader {

    private final ConcurrentMap<String, Object> parallelLockMap;

    protected BaseClassLoader(URL[] urls, ClassLoader parent) {
        super(urls, parent);
        parallelLockMap = new ConcurrentHashMap<String, Object>();
    }

    @Override
    protected Object getClassLoadingLock(String className) {
        Object lock = this;
        if (parallelLockMap != null) {
            Object newLock = new Object();
            lock = parallelLockMap.putIfAbsent(className, newLock);
            if (lock == null) {
                lock = newLock;
            }
        }
        return lock;
    }
}